package com.qining618.common.context;

import com.qining618.common.model.AuthUser;

import javax.servlet.http.HttpServletRequest;

/**
 * @author flt
 * @date 2019-08-16
 */
public class ContextHandle {

    private static final ThreadLocal<AuthUser> AUTH_USER_HOLDER = new ThreadLocal<>();
    private static final ThreadLocal<HttpServletRequest> REQUEST_HOLDER = new ThreadLocal<>();
    private static final ThreadLocal<String> TOKEN_HOLDER = new ThreadLocal<>();

    public static void add(AuthUser authUser) {
        AUTH_USER_HOLDER.set(authUser);
    }

    public static void add(HttpServletRequest request) {
        REQUEST_HOLDER.set(request);
    }

    public static void addToken(String token) {
        TOKEN_HOLDER.set(token);
    }

    public static Long getUserId() {
        AuthUser authUser = getAuthUser();
        if (authUser != null) {
            return authUser.getId();
        }
        return null;
    }

    public static AuthUser getAuthUser() {
        return AUTH_USER_HOLDER.get();
    }

    public static HttpServletRequest getRequest() {
        return REQUEST_HOLDER.get();
    }

    public static String getToken() {
        return TOKEN_HOLDER.get();
    }

    public static void clean() {
        AUTH_USER_HOLDER.remove();
        REQUEST_HOLDER.remove();
        TOKEN_HOLDER.remove();
    }
}
